package com.solocredit.finance.http

import com.solocredit.finance.BuildConfig
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.data.analyse.AnalyseBuilder
import com.solocredit.finance.data.analyse.AnalyseUtil
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONObject
import java.util.Locale
import java.util.Random
import java.util.TimeZone


/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/24 14:12
 * @Annotation：接口API
 */
object ApiService {

    /**
     * http://159.138.165.72
     * https://www.vistafinance.net
     * 域名
     */
    var MULLA_BASE_URL = "https://www.vistafinance.net"

    /**
     * 接口Url
     */
    object API_URL{
        /**
         * 地区转发
         * /v1/timezonePath
         */
        const val MULLA_API_TIMEZONE_URL = "/j4MQbY3vktPTnqeoBNzzA"
        /**
         * APP业务统一请求接口
         * /v1/commonApi
         */
        const val MULLA_API_COMMON_URL = "/k0fNwfNwSofuaFZKuUx5KA"
        /**
         * APP业务统一请求接口（登录）
         * /v1/commonApi
         */
        const val MULLA_API_LOGIN_URL = "/k0fNwfbRl1ymSuKHubYjPD"
        /**
         * 图片上传
         * /v1/imageUpload
         */
        const val MULLA_API_UPLOAD_FILE_URL = "/EZQoCwt627vtLOjhgZCQ"
    }

    /**
     * 数据分析Path
     */
    object ANALYSIS_PATH{

        /**
         * googel install 请求路径
         * /v1/channelInstallTemp
         */
        const val MULLA_ANALYSIS_GOOGLE_INSTALL_PATH = "/yLvhm8Hq1G2uvqgj62CCw"

        /**
         * adjust install 请求路径
         * /v1/adjustInstallTemp
         */
        const val MULLA_ANALYSIS_ADJUST_INSTALL_PATH = "/j1HghoITKtZy18qgXIhZJQ"

        /**
         * facebook install 请求路径
         * /v1/saveFbAppData
         */
        const val MULLA_ANALYSIS_FACEBOOK_INSTALL_PATH = "/YX5l7DgQGQW0yx4hyrmBuw"

        /**
         * firebase 请求路径
         * /v1/fireBase/save
         */
        const val MULLA_ANALYSIS_FIREBASE_INFO_PATH = "/sl49KpX1flNf9C7YhnK0w"

        /**
         * AppList 请求路径
         * /v2/userAppList
         */
        //const val MULLA_DEVICE_ALIST_PATH = "/j21edvbTfCyLiX8ONpMgX9w"

        /**
         * 请求路径
         * /v2/smsRecord
         */
        //const val MULLA_DEVICE_MSG_PATH = "/v7YGCHDLaTzwwIBAEYFwA"

        /**
         * device 请求路径
         * /v1/deviceInfo
         */
        //const val MULLA_DEVICE_DEVICE_PATH = "/NK48KXbp4w06RUHQBIlsA"

        /**
         * battery 请求路径
         * /v1/userDeviceBattery
         */
       //const val MULLA_DEVICE_BATTERY_PATH = "/CIAxCLqpu40aawYC6aq7Og"

        /**
         * hardwave 请求路径
         * /v1/userDeviceHardware
         */
        //const val MULLA_DEVICE_HARDWAVE_PATH = "/Qp8cKrrZuhgZrb48G1Y9A"

        /**
         * contact 请求路径
         * /v2/phoneBookList
         */
        //const val MULLA_DEVICE_PHONEBOOK_PATH = "/h5WcuyoRdyIiJppkQO5tQ"

        /**
         * storge 请求路径
         * /v1/userDeviceStorage
         */
        //const val MULLA_DEVICE_STORGE_PATH = "/a8kY5TLE2Cph3vQiVU0O6w"

        /**
         * wifi 请求路径
         * /v1/userDeviceWifi
         */
        //const val MULLA_DEVICE_WIFI_PATH = "/fS1itWuQN18um54zoKFSA"

        /**
         * calllog 请求路径
         * /v2/callRecord
         */
        //const val MULLA_DEVICE_CALLLOG_PATH = "/FRwxTdpTkXjhFR8nvGJNA"
    }


    /**
     * 接口Path
     */
    object API_PATH{
        /**
         * APP配置参数 Path
         * /v1/getAppShowInfo
         */
        const val MULLA_API_APP_INFO_PATH = "/jxHlzgQNqMeUI5JeH8lRrA"

        /**
         * 发送验证码
         * /v1/smsCode
         */
        const val MULLA_API_SEND_MSG_PATH = "/vAqyrIQFL5zasQlWBHn3kA"

        /**
         * 发送whatsapp验证码
         * /v1/sendWhatAppMessage
         */
        const val MULLA_API_WHATSAPP_SEND_CODE_PATH = "/QBdNPqSFfdLcLFNTXzrt3A"

        /**
         * 校验whatsapp验证码
         *  /v1/checkWhatAppMessageCode
         */
        const val MULLA_API_WHATSAPP_CHECK_CODE_PATH = "/puodSjgJPhMRq8AOrahqBQ"

        /**
         * 登录
         * /v1/userLogin
         */
        const val MULLA_API_LOGIN_PATH = "/HBhGQlny49fzR6KXwHw"

        /**
         * 无验证码登录
         * /v1/userLoginNoCode
         */
        const val MULLA_API_LOGIN_NO_CODE_PATH = "/ZuGgMnVZLgSl03Xhm769cA"

        /**
         * 用户流程状态
         * /v1/userProcess
         */
        const val MULLA_API_PROCESS_PATH = "/fo2Zd6bXzXEMwJWteslmA"

        /**
         * 保存用户图片信息（身份证、护照、驾驶证、人脸）
         * /v1/ocrInfo
         */
        const val MULLA_API_OCR_INFO_PATH = "/Yp7IhcTg0V08tw74rNXVg"

        /**
         * 用户贷款额度
         * /v1/loanLimit
         */
        const val MULLA_API_LIMIT_PATH = "/IrEDpkpM286wBxwKsZxOQ"

        /**
         * 用户贷款额度信息（循环额度）
         * /v1/getLoanHomePage
         */
        const val MULLA_API_LIMIT_LOOP_PATH = "/bGJWLyCPvSsqTZrsiPS5A"

        /**
         * 新用户贷款额度预览信息
         * /v1/getLoanApplyDetail
         */
        const val MULLA_API_ORDER_DETAILS_PATH = "/pKy8rMSN3zsgQTe0PP3Lbg"

        /**
         * 可选额度和期限的预览信息(老用户)
         * /getLoanDetailPageForDays
         */
        const val MULLA_API_APPLY_CUSTOM_LIMIT_INFO_PATH = "/I2ZQc4RSyn9xxKXrzojuwg"

        /**
         * 创建贷款申请订单
         * /v1/loanApply
         */
        const val MULLA_API_APPLY_ORDER_CREATE_PATH = "/y6j8dzci8D21nETtu4iA"

        /**
         * 订单列表
         * /v1/getAllOrderList
         */
        const val MULLA_API_ORDER_LIST_PATH = "/uBO6fRHAkVwDa0m2gGFJA"

        /**
         * 贷款还款信息
         * /v1/repayInfo
         */
        const val MULLA_API_REPAYMENT_INFO_PATH = "/lQofcsoAvnd1W7uQMSucA"

        /**
         * 贷款还款链接
         * /v1/orderRepayH5
         */
        const val MULLA_API_REPAYMENT_URL_PATH = "/NEOkQIYMaiBOJEJXmKoNpA"

        /**
         * 贷款还款链接（肯尼亚、乌干达）
         * /v1/getOrderRepayH5
         */
        const val MULLA_API_REPAYMENT_KSH_UGX_URL_PATH = "/ToQ1YiZTdR4mOOoQ5HonWQ"

        /**
         * 获取支付状态（没有还款链接时，会进入查询支付状态流程）
         * /v1/queryPaymentStatus
         */
        const val MULLA_API_REPAYMENT_STATUS_PATH = "/C2yWJiiDsMky8tayEOX0Ug"

        /**
         * 账户列表
         * /v1/getBindCardList
         */
        const val MULLA_API_ACCOUNT_LIST_PATH = "/wwnCCVTDPY510oh4PSbo5A"

        /**
         * 已绑定账户列表（法语）
         * /v2/fetchBoundBankAccount
         */
        const val MULLA_API_ACCOUNT_LIST_FRENCH_PATH = "/j3z8aqxg8w4ogppBZWOzHnA"

        /**
         * 添加账户(法语地区)
         * /v2/bindBankAccount
         */
        const val MULLA_API_ACCOUNT_ADD_PATH = "/IO56aMSO6WpU3pB9yAzbg"

        /**
         * 删除已绑定的账户
         * /v1/deleteBoundBankAccount
         */
        const val MULLA_API_ACCOUNT_DELETE_PATH = "/QTQnWwOFzMTNbd5M6FeD4w"

        /**
         * 评价弹框
         * /v1/fetchStarWindowConfig
         */
        const val MULLA_API_STAR_COMMENT_PATH = "/YwdWuVdPx7hsmBpdBkJncA"

        /**
         * 提交意见反馈
         * /v1/feedback
         */
        const val MULLA_API_FEEDBACK_SUBMIT_PATH = "/j7daqkSAqNbiX7WJhg4EXQ"

        /**
         * 推荐APP列表
         * /v1/userDeniedDc
         */
        const val MULLA_API_RECOMMEND_APP_LIST_PATH = "/Pl3uPSqgaR5xmlwmS15w"
        /**
         * 事件埋点
         * /v1/userBuriedPoint
         */
        const val MULLA_API_TRACK_EVENT_PATH = "/CbUiFGi3qFfHoFxN3BI8A"
        /**
         * 事件批量埋点
         * v1/userBuriedPointForBatch
         */
        const val MULLA_API_TRACK_EVENT_BATCH_PATH = "/EgqdZPoVpZxuZgX1blOv2Q"

        /**
         * 消息列表
         * /v1/fetchUserMessages
         */
        const val MULLA_API_MESSAGE_LIST_PATH = "/YeYBPLpioh0z4F5uT0bQ"

        /**
         * 产品列表
         * /queryNewStyleProducts
         */
        const val MULLA_API_PRODUCT_LIST_PATH = "/YUtAPPzWAPFvYsJO4VaA"

        /**
         *  复制产品A信息 到 产品B (配置信息、进件信息)
         *  /oneKeyCopyToApply
         */
        const val MULLA_API_PRODUCT_COPY_PATH = "/tnfWPibeUvt0ZlhqqOSYVA"

        /**
         * 优惠券列表
         * /v1/getUserCouponAndScoreInfo
         */
        const val MULLA_API_COUPON_LIST_PATH = "/MHSKzXuEMEz5slss6YpSA"

        /**
         * 签到信息
         * /v1/userSign
         */
        const val MULLA_API_SIGN_PATH = "/OwtLFb7oBTBfUgxvASddw"

        /**
         *  存取积分、优惠券兑换
         *  /v1/changeUserScore
         */
        const val MULLA_API_SAVE_OR_USE_PATH = "/Fz7cn3gafinBXVgqVcXmA"

        /**
         * 保存自定义参数接口
         * /v1/saveAbUserInfo
         */
        const val MULLA_API_SAVE_CUSTOM_PARAMS_PATH = "/nejuOWsVgHP92SeIO4Tgjg"

        /**
         * 获取自定义参数
         * /v1/getAbUserInfo
         */
        const val MULLA_API_LOAD_CUSTOM_PARAMS_PATH = "/2SD9BoxOAkMu9gw8iDjNaA"

        /**
         * 清除用户数据
         * /v1/userCancel
         */
//        const val MULLA_API_USER_DATA_CLEAR_PATH = "/ngeeyctlQMOKWF9zH1mWRg"

        /**
         * 清除用户数据(新)
         * /v1/dropUserData
         */
        const val MULLA_API_USER_DATA_CLEAR_PATH = "/kO6wzbvufjLN34U4f936nQ"

        /**
         * 设备数据上传状态
         * /v1/queryDeviceInfoTypes
         */
        const val MULLA_API_DEVICE_INFO_TYPES_PATH = "/oWP97pmU6DdtsNHL13R35Q"

    }

    /**
     * 获取请求Url
     */
    fun getHttpUrl(url: String): String{
        //地区转发
        val timeZone = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE)
        if (timeZone.isNotEmpty()){
            return "$MULLA_BASE_URL/$timeZone$url"
        }
        return "$MULLA_BASE_URL$url"
    }

    /**
     * 添加公共参数
     */
    fun JSONObject.addCommonParams(): JSONObject {
        apply {
            put("product", MullaConfigs.MULLA_APPNAME)                                           //  产品 APP名称
            put("token", SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_TOKEN))                                               //  token
            put("apiVersion","v3")                                                      //  接口版本
            put("androidId", AnalyseUtil.getAndroidId())                                    //  安卓id
            put("advertId", AnalyseUtil.getAdId())                                          //  广告id
            put("aduid", AnalyseUtil.getAdId())                                             //  广告id
            put("aduidPath", AnalyseUtil.getAndroidId())                                    //  广告地址
            put("isLimitAdTrackingEnabled", AnalyseUtil.getAdEnabled().toString())          //  是否限制广告id，1是 0否
            put("userId", SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_USERID))                                             //  userId
            put("version", BuildConfig.VERSION_CODE)                                        //  app版本号
            put("country", SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_COUNTRY))                                  //国家标识
            put("tzid", TimeZone.getDefault().id)                                             //当前时区id
            put("localTimestamp","${System.currentTimeMillis()}")                       //时间戳
            put("lang", Locale.getDefault().language)
        }
        return this
    }

    /**
     * 添加随机参数增量 8
     */
    fun JSONObject.addRandomParams(): JSONObject{
        val mobile = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_MOBILE)
        val timeStamp = System.currentTimeMillis() / 1000
        apply {
            put("loginName",mobile)
            put("loginTimeStamp",timeStamp)
            put("signName", AnalyseBuilder.product)
            put("signTimeStamp",timeStamp)
            put("luckyDrawName", AnalyseBuilder.product)
            put("luckyDrawTimeStamp",timeStamp)
            put("applyName", AnalyseBuilder.product)
            put("applyTimeStamp",timeStamp)
//            for (i in 0..7){
//                val addKey = getMullaRandomKey(1+Random().nextInt(4))
//                val addValue = getMullaRandomKey(1+Random().nextInt(16))
//                put(addKey.lowercase(),addValue.lowercase())
//            }
        }
        return this
    }

    /**
     * 随机字符串
     */
    private fun getMullaRandomKey(length: Int): String {
        val charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
        val stringBuilder = StringBuilder()
        val random = Random()
        for (i in 0..length){
            val index = random.nextInt(charSet.length)
            stringBuilder.append(charSet[index]);
        }
        return stringBuilder.toString();
    }
}